﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.UI.WebControls;
using VaccineEbook.Models;
using VaccineEbook.Models.DBEntity;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Text;


namespace VaccineEbook.Controllers
{
    // Chuyện gì xảy ra với chapter id ???
    public class ChapterController : Controller
    {
        string _messageError = "";
        //
        // GET: /Chapper/

        public ActionResult Index(int? page)
        {
            string searchString = Request.QueryString[Constant.QUICK_SEARCH_STRING];
            ViewBag.MessageSuccess = TempData["MessageSuccess"];
            _messageError = (String)TempData["MessageError"] ?? "";

            IEnumerable<PROC_ChapterGroup_Result> listChapter = PROC_ChapterGroup_Result.QuickSearch(searchString, 1, ref _messageError);
            if (listChapter != null)
            {
                int intPage = page ?? 1;
                CustomPageList<PROC_ChapterGroup_Result> pagelist = new CustomPageList<PROC_ChapterGroup_Result>(listChapter, intPage, Models.Constant.DEFAUT_PAGESIZE);
                return View(pagelist);
            }

            ViewBag.MessageError = _messageError;
            return View();
        }

        [ChildActionOnly]
        public ActionResult _MenuChapterPartial()
        {
            IEnumerable<PROC_ChapterGroup_Result> listChapterGroup = PROC_ChapterGroup_Result.QuickSearch("", 1, ref _messageError);
            IEnumerable<ChapterModel.ChapterMenuModel> listMenu = listChapterGroup.Select(m => new ChapterModel.ChapterMenuModel()
            {
                ID = m.ID,
                ChapterGroup = m.ChappterGroup,
                Page = m.Page,
                ChapterID = m.ChapterID
            });
            return View(listMenu);
        }

        [ChildActionOnly]
        public ActionResult _ListChapterGroupPartial(int? ChapterID)
        {
            IEnumerable<Chapter> listChapter = Chapter.GetByChapterID(1, ChapterID.GetValueOrDefault(), ref _messageError);
            IEnumerable<ChapterModel.ChapterMenuModel> listMenu = listChapter.Select(m => new ChapterModel.ChapterMenuModel()
            {
                ID = m.ID,
                ChapterGroup = m.ChappterGroup,
                Page = m.Page,
                ChapterID = m.ChapterID
            });
            return View(listMenu);
        }

        public ActionResult Edit(int? id, int? ChapterID)
        {
            ChapterModel.EditChapterModel editModel = new ChapterModel.EditChapterModel();
            if (id == null)
            {
                // init interface add new chapter
                if (ChapterID == null)
                {
                    #region add new with new chaptergroup, chapterid
                    editModel.Page = Chapter.GetMaxPage(1) + 1;
                    #endregion
                }
                else
                {
                    #region add new width exist chaptergroup, chapterid
                    IEnumerable<Chapter> listChapter = Chapter.GetByChapterID(1, ChapterID.GetValueOrDefault(), ref _messageError);
                    if (listChapter == null)
                    {
                        // chapterid not exist
                        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                    }
                    else
                    {
                        Chapter lastChapter = listChapter.Last();
                        editModel.ChapterGroup = lastChapter.ChappterGroup;
                        editModel.Page = lastChapter.Page + 1;
                        editModel.ChapterID = ChapterID.GetValueOrDefault();
                    }
                    #endregion
                }
            }
            else
            {
                #region init interface edit chapter
                Chapter chapter = Chapter.GetByID(id.Value, ref _messageError);
                if (chapter == null)
                {
                    // không tìm thấy
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                // change type
                editModel = new ChapterModel.EditChapterModel()
                {
                    ID = chapter.ID,
                    Icon = chapter.Icon,
                    Page = chapter.Page,
                    ChapterID = chapter.ChapterID.GetValueOrDefault(),
                    ChapterGroup = chapter.ChappterGroup,
                    ChapterContent = chapter.ChapterContent,
                    ChapterDescription = chapter.ChapterDescription,
                };
                #endregion
            }
            return View(editModel);
        }

        [HttpPost]
        public ActionResult Edit(ChapterModel.EditChapterModel model)
        {
            if (ModelState.IsValid)
            {
                // init
                Chapter chapter = new Chapter()
                {
                    ID = model.ID,
                    Icon = model.Icon,
                    ChapterContent = model.ChapterContent,
                    ChapterDescription = model.ChapterDescription,
                };

                if (model.ID <= 0)
                {
                    // add new action
                    string username = System.Web.HttpContext.Current.User.Identity.Name;
                    Models.DBEntity.User user = Models.DBEntity.User.GetBy_Username(username, ref _messageError);

                    if (model.ChapterID <= 0)
                    {
                        // TODo: do this
                        #region add new width new chapterid
                        chapter.ChappterGroup = model.ChapterGroup;
                        chapter.Page = Chapter.GetMaxPage(1) + 1;
                        chapter.ChapterID = Chapter.GetMaxChapterID(1) + 1;
                        #endregion
                    }
                    else
                    {
                        #region add new width exist chapterid
                        IEnumerable<Chapter> listChapter = Chapter.GetByChapterID(1, model.ChapterID, ref _messageError);
                        if (listChapter == null)
                        {
                            // chapterid not exist
                            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                        }
                        Chapter lastChapter = listChapter.Last();
                        chapter.ChappterGroup = lastChapter.ChappterGroup;
                        chapter.Page = lastChapter.Page + 1;
                        chapter.ChapterID = lastChapter.ChapterID;
                        #endregion
                    }

                    #region Save
                    // NOTE: defaut bookid = 1, add page form 1 => max book + 1
                    chapter.BookID = 1;
                    Chapter.AddNew(chapter, user.UserID, ref _messageError);

                    if (chapter != null)
                    {
                        // return new page
                        return RedirectToAction("Edit", new { id = chapter.ID, ChapterID = chapter.ChapterID });
                    }
                    #endregion
                }
                else
                {
                    #region update action
                    chapter = Chapter.Update(model.ID, chapter, ref _messageError);
                    if (chapter != null)
                    {
                        // save success
                        ViewBag.MessageSuccess = "Saved";
                    }
                    #endregion
                }
            }
            ModelState.AddModelError("", _messageError);
            return View(model);

            //if (ModelState.IsValid)
            //{
            //    // init
            //    Chapter chapter = new Chapter()
            //    {
            //        ID = model.ID,
            //        Icon = model.Icon,
            //        ChappterGroup = model.ChapterGroup,
            //        ChapterContent = model.ChapterContent,
            //        ChapterDescription = model.ChapterDescription,
            //    };

            //    if (model.ID <= 0)
            //    {
            //        // save add new,
            //        string username = System.Web.HttpContext.Current.User.Identity.Name;
            //        Models.DBEntity.User user = Models.DBEntity.User.GetBy_Username(username, ref _messageError);
            //        // NOTE: defaut bookid = 1, add page form 1 => max book + 1
            //        chapter.Page = model.Page;
            //        chapter.BookID = 1;
            //        chapter = Chapter.AddNew(chapter, user.UserID, ref _messageError);
            //    }
            //    else
            //    {
            //        // save edit, NOTE: Page, bookID not change, update all book page after
            //        chapter = Chapter.Update(model.ID, chapter, ref _messageError);
            //    }

            //    if (chapter != null)
            //    {
            //        // save success
            //        TempData["MessageSuccess"] = "Save success";
            //        return RedirectToAction("Index");
            //    }
            //}

            //ModelState.AddModelError("", _messageError);
            //return View(model);
        }


        public ActionResult Delete(int? id, int? ChapterID)
        {
            // chapterID => return page if fail
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Chapter chapter = Chapter.Delete(id.GetValueOrDefault(), ref _messageError);
            if (chapter != null)
            {
                // success => home
                return RedirectToAction("Index");
            }
            else
            {
                // faise => return
                ModelState.AddModelError("", _messageError);
                return RedirectToAction("Edit", new { id = id, ChapterID = ChapterID });
            }
        }

        public ActionResult DeleteChapterGroup(int? ChapterGroupID)
        {
            if (ChapterGroupID == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            bool result = Chapter.DeleteByChapterGroup(1, ChapterGroupID.GetValueOrDefault(), ref _messageError);

            TempData["MessageError"] = _messageError;
            return RedirectToAction("Index");
        }

        public ActionResult Notification()
        {

            try
            {
                // Push notification IOS
                IEnumerable<Token> strDeviceToken = VaccineEbook.Models.DBEntity.User.GetAllToken(ref _messageError);
                string strPushMessage = "Please update you data!";
                string _tokenId = null;
                var notificationList = new List<MoonAPNS.NotificationPayload>();
                string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Certificate/PushPocketGuideKey_Development.p12");
                string certificatePath = System.Web.HttpContext.Current.Server.MapPath("Certificate/PushPocketGuideKey_Development.p12");
                X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(path), "123456789");

                // setting for android
                string applicationID = "AIzaSyAO9QqZQ_yNOrqZkDKDOIXCavuk-lSdkT0";
                string SENDER_ID = "680294466851";
                List<string> listRegid = new List<string>();
                string[] arrRegid = null;

                if (strDeviceToken != null)
                {
                    foreach (Token token in strDeviceToken)
                    {
                        if (token.type == 0)
                        {
                            // push ios
                            _tokenId = token.tokenID;
                            var payload = new MoonAPNS.NotificationPayload(_tokenId, strPushMessage, 1, "default"); // 51 is the badge no
                            payload.AddCustom("RegionID", "IDQ10150");
                            notificationList.Add(payload);
                        }
                       else if(token.type == 1) 
                        {
                            // push android
                            listRegid.Add(token.tokenID);

                        }
                    }
                }
                
                //push ios
                if (notificationList.Count() > 0)
                {
                    var push = new MoonAPNS.PushNotification(true, certificatePath, "123456789", clientCertificate);
                    push.P12File = path;// @"D:\Moon-APNS-master\WebApplication1\Cer\PushPocketGuide3.p12";
                    push.P12FilePassword = "123456789";
                    var result = push.SendToApple(notificationList);
                    // Done push IOS!
                }
                if (listRegid.Count() > 0)
                {
                    arrRegid = listRegid.ToArray();
                    //push android
                    WebRequest tRequest;
                    // thiet lap GCm send
                    tRequest = HttpWebRequest.Create("https://android.googleapis.com/gcm/send");
                    tRequest.Method = "POST";
                    tRequest.UseDefaultCredentials = true;
                    tRequest.PreAuthenticate = true;
                    tRequest.Credentials = CredentialCache.DefaultNetworkCredentials;                    
                    //tRequest.Credentials = new NetworkCredential("admin", "123");                   
                    //định dạng JSON
                    tRequest.ContentType = "application/json";
                    //tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
                    tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
                    tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
                    string RegArr = string.Empty;
                    RegArr = string.Join("\",\"", arrRegid);
                    string postData = "{ \"registration_ids\": [ \"" + RegArr + "\" ],\"data\": {\"message\": \"" + strPushMessage + "\",\"collapse_key\":\"" + strPushMessage + "\"}}";
                    //Console.WriteLine(postData);
                    Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                    tRequest.ContentLength = byteArray.Length;
                    Stream dataStream = tRequest.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();

                    WebResponse tResponse = tRequest.GetResponse();
                    dataStream = tResponse.GetResponseStream();
                    StreamReader tReader = new StreamReader(dataStream);
                    String sResponseFromServer = tReader.ReadToEnd();

                    tReader.Close();
                    dataStream.Close();
                    tResponse.Close();
                    // Done push ANDROID!
                }
                TempData["MessageSuccess"] = "Successful Push Messaging";
                //Response.Write(@"<script language='javascript'>alert('Successful Push Messaging')</script>");                
            }
            catch (Exception ex)
            {
                string msgError = ex.ToString();
                //Response.Write(@"<script language='javascript'>alert('" + msgError + "')</script>");
                _messageError = msgError;
                TempData["MessageError"] = _messageError;                
            }
            return RedirectToAction("Index");            
        }
    }
}
